//
//  WeiboCell.m
//  Project_2_weibo
//
//  Created by 林林 on 16/6/20.
//  Copyright © 2016年 lhn. All rights reserved.
//

#import "WeiboCell.h"
#import "UIImageView+WebCache.h"
#import "NSDate+TimeAgo.h"
#import "WeiboCellLayout.h"
#import "RegexKitLite.h"
#import "WeiboWebViewController.h"

@implementation WeiboCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // 设置cell样式
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.contentView.backgroundColor = [UIColor clearColor];
    self.userImageView.layer.cornerRadius = 5;
    self.userImageView.layer.masksToBounds = YES;
    
    //设置字体颜色
    _timeLabel.colorName = @"Timeline_Time_color";
    _sourceLabel.colorName = @"More_Item_Text_color";
    _usernameLabel.colorName = @"More_Item_Text_color";
    
    //监听主题改变通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(themeChanged) name:kThemeChangedNotificationName object:nil];
    
    [self themeChanged];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)themeChanged {
    
    //改变颜色
    self.weiboTextLabel.textColor = [[ThemeManager sharedManager] themeColorWithColorName:@"Timeline_Content_color"];
    self.reWeiboTextLabel.textColor = [[ThemeManager sharedManager] themeColorWithColorName:@"Detail_Content_color"];
    
}

#pragma mark - 创建子视图 懒加载
- (WXLabel *)weiboTextLabel {
    
    if (_weiboTextLabel == nil) {
        //创建对象
        _weiboTextLabel = [[WXLabel alloc] initWithFrame:CGRectMake(10, 75, kScreenWidth - 20, 0)];
        _weiboTextLabel.font = [UIFont systemFontOfSize:16];
        _weiboTextLabel.numberOfLines = 0;
        _weiboTextLabel.wxLabelDelegate = self;
        _weiboTextLabel.linespace = 5;
        [self.contentView addSubview:_weiboTextLabel];
    }
    return _weiboTextLabel;
}

//- (UIImageView *)weiboImageView {
//    
//    if (_weiboImageView == nil) {
//        
//        _weiboImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
//        [self.contentView addSubview:_weiboImageView];
//    }
//    return _weiboImageView;
//}

- (NSArray *)images {
    if (_images == nil && _images.count != 9) {
        
        NSMutableArray *mArray = [NSMutableArray array];
        for (int i = 0; i < 9; i++) {
            UIImageView *imageView = [[UIImageView alloc] init];
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            imageView.layer.masksToBounds = YES;
            [self.contentView addSubview:imageView];
            imageView.backgroundColor = [UIColor orangeColor];
            [mArray addObject:imageView];
            
            //添加点击手势
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
            //开启用户点击事件
            imageView.userInteractionEnabled = YES;
            [imageView addGestureRecognizer:tap];
            //添加tag值
            imageView.tag = i;
            
        }
        
        _images = [mArray copy];
    }
    
    return _images;
}

//转发的微博
- (WXLabel *)reWeiboTextLabel {
    if (_reWeiboTextLabel == nil) {
        _reWeiboTextLabel = [[WXLabel alloc] init];
        _reWeiboTextLabel.font = kReWieboTextFont;
        _reWeiboTextLabel.numberOfLines = 0;
        _reWeiboTextLabel.wxLabelDelegate = self;
        _reWeiboTextLabel.linespace = 3;
        [self.contentView addSubview:_reWeiboTextLabel];
    }
    return _reWeiboTextLabel;
}

- (ThemeImageView *)reWeiboBgImageView {
    if (_reWeiboBgImageView == nil) {
        _reWeiboBgImageView = [[ThemeImageView alloc] init];
        _reWeiboBgImageView.imageName = @"timeline_rt_border_9.png";
        _reWeiboBgImageView.leftCapWidth = 10;
        _reWeiboBgImageView.topCapHeight = 10;
        
        [self.contentView insertSubview:_reWeiboBgImageView atIndex:0];
    }
    return _reWeiboBgImageView;
}
#pragma mark - 填充数据
- (void)setWeiboModel:(Weibo *)weiboModel {
    
    if (_weiboModel != weiboModel) {
        _weiboModel = weiboModel;
        
        //----------------------固定视图---------------------------
        //设置数据
        _usernameLabel.text = _weiboModel.user.screen_name;
        NSURL *imageUrl = [NSURL URLWithString:_weiboModel.user.profile_image_url];
        [_userImageView sd_setImageWithURL:imageUrl];
        //设置时间和来源
        _sourceLabel.text = _weiboModel.source;

        //时间格式转化
        //创建格式对象
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        //设置格式
        [formatter setDateFormat:@"E M dd HH:mm:ss Z yyyy"];
        //字符串->NSDate
        NSDate *date = [formatter dateFromString:_weiboModel.created_at];
        //用第三方
        _timeLabel.text = [date timeAgo];
        
        //微博来源设置
        //<a href="http://app.weibo.com/t/feed/3o33sO" rel="nofollow">iPhone 6</a>
        NSString *source = _weiboModel.source;
        NSRange range1 = [source rangeOfString:@">"];
        NSRange range2 = [source rangeOfString:@"</a>"];
        if (range1.location == NSNotFound || range2.location == NSNotFound) {
            _sourceLabel.text = nil;
        } else {
            NSRange range = NSMakeRange(range1.location + 1, range2.location - range1.location - 1);
            source = [source substringWithRange:range];
            _sourceLabel.text = source;
        }
        
        //填充图片数据
        NSArray *imageUrlArray;
        if (_weiboModel.bmiddle_pic) {
            //填充当前微博中的图片
            imageUrlArray = [_weiboModel.pic_urls copy];
        } else if (_weiboModel.retweeted_status.bmiddle_pic) {
            //填充转发微博中的图片
            imageUrlArray = [_weiboModel.retweeted_status.pic_urls copy];
        } else {
            //没有图片
            imageUrlArray = nil;
        }
        
        //------------------------创建布局对象-------------------------
        WeiboCellLayout *layout = [WeiboCellLayout weiboCellLayoutWithWeiboModel:_weiboModel];
        //-------------------------填充数据-----------------------------
        self.weiboTextLabel.text = _weiboModel.text;
        self.reWeiboTextLabel.text = _weiboModel.retweeted_status.text;
//        NSURL *url = [NSURL URLWithString:_weiboModel.bmiddle_pic];
//        [self.weiboImageView sd_setImageWithURL:url];
        //---------------------------布局---------------------------------
        self.weiboTextLabel.frame = layout.weiboTextFrame;
        self.reWeiboTextLabel.frame = layout.reWeiboTextFrame;
        self.reWeiboBgImageView.frame = layout.reWeiboBgImageViewFrame;
//        self.weiboImageView.frame = layout.weiboImageViewFrame;
        
        //九个图片布局
        for (int i = 0; i < 9; i++) {
            //取出frame
            CGRect frame = [layout.imagesFrameArray[i] CGRectValue];
            //取出imageview
            UIImageView *imageView = self.images[i];
            if (i < imageUrlArray.count) {
                //获取图片url地址
                NSDictionary *dic = imageUrlArray[i];
                NSString *urlString = dic[@"thumbnail_pic"];
                [imageView sd_setImageWithURL:[NSURL URLWithString:urlString]];
                
            }
            imageView.frame = frame;
        }

    }
}

#pragma mark - WXLabelDelegate
- (NSString *)contentsOfRegexStringWithWXLabel:(WXLabel *)wxLabel {
    NSString *regex = [NSString stringWithFormat:@"(%@)|(%@)|(%@)", @"#[^#]+#", @"@[\\w-]{2,30}[\\s:]", @"http(s)?://([a-zA-Z0-9._-]+(/)?)+"];
    return regex;
}
//设置当前链接文本的颜色
- (UIColor *)linkColorWithWXLabel:(WXLabel *)wxLabel {
    return [[ThemeManager sharedManager] themeColorWithColorName:@"Link_color"];
}
//设置当前文本手指经过的颜色
- (UIColor *)passColorWithWXLabel:(WXLabel *)wxLabel {
    return [UIColor redColor];
}

- (void)toucheEndWXLabel:(WXLabel *)wxLabel withContext:(NSString *)context {
    
    NSString *regex = @"http(s)?://([a-zA-Z0-9._-]+(/)?)+";
    if ([context isMatchedByRegex:regex]) {
        
        WeiboWebViewController *webVC = [[WeiboWebViewController alloc] initWithURL:[NSURL URLWithString:context]];
        webVC.hidesBottomBarWhenPushed = YES;
        [[self navigationController] pushViewController:webVC animated:YES];
    } else if ([context isMatchedByRegex:@"@[\\w-]{2,30}[\\s:]"]) {
        NSLog(@"@用户");
    } else if ([context isMatchedByRegex:@"#[^#]+#"]) {
        NSLog(@"主题");
    }
    
}

- (UINavigationController *)navigationController {
    
    UIResponder *nextResponder = self.nextResponder;
    while (nextResponder) {
        if ([nextResponder isKindOfClass:[UINavigationController class]]) {
            return (UINavigationController *)nextResponder;
        }
        nextResponder = nextResponder.nextResponder;
    }
    return nil;
}

#pragma mark - 点击手势
- (void)tapAction:(UITapGestureRecognizer *)tap {
    
    [WXPhotoBrowser showImageInView:self.window
                   selectImageIndex:tap.view.tag
                           delegate:self];
    
}

#pragma mark - PhotoBrowerDelegate

//需要显示的图片个数
- (NSUInteger)numberOfPhotosInPhotoBrowser:(WXPhotoBrowser *)photoBrowser {
    
    if (_weiboModel.retweeted_status && _weiboModel.retweeted_status.pic_urls) {
        return _weiboModel.retweeted_status.pic_urls.count;
    } else if (_weiboModel.pic_urls) {
        return _weiboModel.pic_urls.count;
    }
    return 0;
}

//返回需要显示的图片对应的Photo实例,通过Photo类指定大图的URL,以及原始的图片视图
- (WXPhoto *)photoBrowser:(WXPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    
    WXPhoto *photo = [[WXPhoto alloc] init];
    
    NSString *urlString;
    if (_weiboModel.retweeted_status && _weiboModel.retweeted_status.pic_urls) {

        urlString = _weiboModel.retweeted_status.pic_urls[index][@"thumbnail_pic"];
        NSLog(@"1---%@", urlString);
    } else if (_weiboModel.pic_urls) {

        urlString = _weiboModel.pic_urls[index][@"thumbnail_pic"];
        NSLog(@"1---%@", urlString);
    }
    urlString = [urlString stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"large"];
    NSLog(@"2---%@", urlString);
    photo.url = [NSURL URLWithString:urlString];
    photo.srcImageView = _images[index];
    
    return photo;
}

#pragma mark -

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end





